package com.thx.common.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.thx.common.log.annotation.Log;
import com.thx.common.struts2.CurdAction;
import com.thx.common.util.ReflectionUtils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 日志拦截器.
 *
 * @author niuhm
 */
public abstract class LogInterceptor extends AbstractInterceptor {

  private static final long serialVersionUID = 984150653349868650L;

  private static Logger log = LoggerFactory.getLogger(LogInterceptor.class);

  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();
    CurdAction baseAction = null;
    if (action instanceof CurdAction) {
      baseAction = (CurdAction) action;
    }
    String result = invocation.invoke();
    Method method = invocation.getAction().getClass()
        .getMethod(invocation.getProxy().getMethod());
    Annotation annotation = method.getAnnotation(Log.class);
    if (annotation != null) {
      Log logAnnotation = (Log) annotation;
      try {
        //附带属性参数的
        if (StringUtils.isNotBlank(logAnnotation.multiField())) {
          Object obj = ReflectionUtils.getFieldValue(baseAction,
              logAnnotation.multiField());
          if (obj != null && NumberUtils.isNumber(obj.toString())) {
            //单参数的
            print(logAnnotation.action(), obj.toString());

          } else if (obj != null && obj instanceof String) {
            String[] ids = obj.toString().split("[,{}]");
            for (String string : ids) {
              if (StringUtils.isNotBlank(string)) {
                print(logAnnotation.action(), string);
              }
            }
          } else if (obj != null) {
            String str = ArrayUtils.toString(obj);
            String[] ids = str.split("[,{}]");
            for (String string : ids) {
              if (StringUtils.isNotBlank(string)) {
                print(logAnnotation.action(), string);
              }
            }
          }
        } else {
          //默认的
          print(logAnnotation.action(), baseAction.getId());
        }
      } catch (Exception ex) {
        log.error("", ex);
      }
    }
    return result;
  }

  public abstract void print(String action, String id);
}
